package com.hystrix.command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 自定义Command
 * Created by earl on 2018/4/28.
 */
public class HelloCommand extends HystrixCommand <String> {


    private String url;
    CloseableHttpClient closeableHttpClient;

    public HelloCommand(String url){
        //调用父类的构造器，设置命令组的key，默认用来作为线程池的key
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
       //创建HttpClient客户端
        this.closeableHttpClient = HttpClients.createDefault();
        this.url = url;
    }


    @Override
    protected String run() throws Exception {
        //调用GET方法请求服务
        HttpGet httpGet = new HttpGet(url);
        //得到响应
        HttpResponse response = closeableHttpClient.execute(httpGet);
        //解析返回的结果
        return EntityUtils.toString(response.getEntity());
    }

    //测试回退
    @Override
    protected String getFallback() {
        System.out.println("执行 HelloCommand 的回退方法");
        //把消息返回到请求的客户端
        return "error";
    }

}
